//
//  ComposeController.swift
//  sina
//
//  Created by 江先铨 on 15/11/19.
//  Copyright © 2015年 jxqstatic. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeController: UIViewController {
    
//    private lazy var keyBoardView: EmotionKeyBoardView = EmotionKeyBoardView {[weak self] (em) -> () in
//        self?.textView.insertAttrText(em)
//    }
    
    //懒加载 键盘的view 并且给键盘的textView 赋值
    private lazy var keyBoardView: EmotionKeyBoardView = EmotionKeyBoardView { (em) -> () in
        //设置textview 显示图片表情
        self.textView.insertAttrText(em)
    }
    

    
    //添加坚挺方法  实现选择图片控制器的方法
    @objc private func selectPicture() {
    
      selectorVC.view.snp_updateConstraints { (make) -> Void in
        
            make.height.equalTo(224 + 80 + 40)
        }
    }
    
    //当点击按钮 弹出是否选择表情图片的一些功能
    @objc private func selectEmoticon() {
    
         //如果是默认键盘  键盘的inputview 是nil   也就是 默认是为空的
        
         //取消第一响应者 取消按钮图片的第一响应者
         textView.resignFirstResponder()
        //设置输入视图 每当点击一次 键盘就弹出返回一次 每一次弹出都是一个点击按钮的事件
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        //让textview 成为第一响应者
        textView.becomeFirstResponder()

    }
    
    
    @objc private func close() {
       
         dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
    
//        let urlString = "2/statuses/update.json"
//        guard let token = ViewModel().token  else {
//        
//           SVProgressHUD.showErrorWithStatus("你还未登录")
//            return
//        }
//        
//        let parmaters = ["access_token" : token, "status": textView.text]
//        
//        Networking.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
//            
//            if error != nil {
//              SVProgressHUD.showErrorWithStatus(AppErrorTip)
//                
//                return
//            }
//            
//            SVProgressHUD.showSuccessWithStatus("发布微博成功")
//            self.dismissViewControllerAnimated(true, completion: nil)
//            
//        }
        //这个判断的是不是一条上传图片的微博  数据
        //定义一个可变的网路的字符串
        var urlString = ""
    
        guard let token = ViewModel().token  else {
        
           SVProgressHUD.showErrorWithStatus("请重新登录")
           return
        }
        //设置请求参数 获得字符串的一些参数
        let paramaters = ["access_token" : token, "status" : textView.fullText()]

        //判断当前的image 是否有值
        if selectorVC.imageList.count >= 1 {
         
         urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            //为什么这个是数组的第0 个数据
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            
           Networking.sharedTools.uploadImage(urlString, parmaters: paramaters, imageData: imageData!, finished: { (result, error) -> () in
            if error != nil {
            
               SVProgressHUD.showErrorWithStatus("你还没有登录")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
             self.dismissViewControllerAnimated(true, completion: nil)
            
           })
        } else {
            //发布一条新微薄  这个微薄是不带图片的微博
            let  urlString = "2/statuses/update.json"
           // let paramaters = ["access_token" : token ,"status" : textView.text]
            
           Networking.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: paramaters, finshed: { (result, error) -> () in
            
            if error != nil {
            
               SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            self.dismissViewControllerAnimated(true, completion: nil)
            
           })
        
        }
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.cyanColor()
        setupUI()
        //让text 成为第一响应者 当点击按钮的时候键盘自动弹出来 就可以了
        textView.becomeFirstResponder()
    }

    private func setupUI() {
    
         setNavBar()
        
         setupTextView()
        
         setupToolBar()
        
        setSelectorView()
        
        registerNotification()
    }
    
    private func setSelectorView() {
    
     //添加子视图控制器
     addChildViewController(selectorVC)
     //添加视图
     view.addSubview(selectorVC.view)
     //调整视图层次结构
      view.bringSubviewToFront(toolBar)
        
        
      selectorVC.view.snp_makeConstraints { (make) -> Void in
           make.left.bottom.right.equalTo(view)
           make.height.equalTo(0)
        }
    }
    
    
    private func registerNotification() {
        //添加通知  这这里 这个通知是键盘的frame的值将要改变的时候
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知观察者
    deinit {
    
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知响应方法
   @objc  private func keyBoardWillChange(n: NSNotification) {
       
        //获取动画事件 key值需要自己敲出来
      let duration =  n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
      //这个key 值是frame 结束值的key值  这个键值是键盘的frame值改变之后的rect
      let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //修改toolBar 的约束
        //获取键盘的高度
        let offset = -screenH + rect.origin.y
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新
            self.view.layoutIfNeeded()
        }
        
    }
    
    //懒加载控件  懒加载textView 这个控件
    private lazy var textView: EmotionTextView = {
        let tv = EmotionTextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //设置键盘消失模式 键盘消失的模式为拖拽  当拖拽屏幕的时候 键盘消失
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启  需要设置弹簧的开启 这样数据才会有效果
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
        }()
    
    
       private lazy var placeHolderLable: UILabel = UILabel(title: "分享新鲜事", size: 18, color: UIColor.lightGrayColor())
       //实例化一个工具条
       private lazy var toolBar: UIToolbar = UIToolbar()
       //实例化一个照片选择器
        private lazy var selectorVC: pictureSelector = pictureSelector()
    
}


extension ComposeController: UITextViewDelegate {

    func textViewDidChangeSelection(textView: UITextView) {
          placeHolderLable.hidden = textView.hasText()
        
          self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}


extension ComposeController {
    
    private func  setupToolBar() {
    
        
       view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        //设置toolbar 的按钮 以及点击事件
        var items = [UIBarButtonItem]()
        //添加 uibar 在这里是一个按钮数组 数组中包含的时按钮的图片的字典
        let itemSettings =  [["imageName": "compose_toolbar_picture", "actionName" : "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            
            //当点击emoji 的表情的时候 就开始实现响应方法 让键盘成为第一响应者
            ["imageName": "compose_emoticonbutton_background","actionName" : "selectEmoticon"],
            
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
           //设置btn 的类型为自定义类型的数据
//           let btn = UIButton(type: .Custom)
//           let imageName = dict["imageName"]!
//           btn.setImage(UIImage(named: imageName), forState: .Normal)
//           btn.setImage(UIImage(named: imageName + "_highlighted"), forState:.Highlighted)
//            btn.sizeToFit()
            
            //把设置好的按钮添加到自定义的view 上面
          //  let item = UIBarButtonItem(customView: btn)
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self , actionName: dict["actionName"])
            items.append(item)
            //实例化一个弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
         
        }
        items.removeLast()
        toolBar.items = items
    }

    private func setupTextView() {
        
        view.addSubview(textView)
        textView.backgroundColor = UIColor.randomColor()
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            //设置text 的高度为原来的1 / 3
            
            make.height.equalTo(view.bounds.height / 3)
        }
        
        textView.addSubview(placeHolderLable)
        placeHolderLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        //创建一个标题的titleView  因为不能直接在导航栏的标题栏上直接添加一个label
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        titleView.backgroundColor = UIColor.lightGrayColor()
        
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        
        let nameLabel = UILabel(title: ViewModel().name ?? "", size: 14, color: UIColor.darkGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
            
        }
    }
    
   


}


